<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;

class File extends Controller
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index($currdir=null)
    {
        $currdir=urldecode($currdir);
        $currdir=iconv('UTF-8','GB2312',$currdir);
        if($currdir){
            if(file_exists($currdir)){
                //查看权限限制
                if(stripos($currdir,ROOT_PATH)===0 && stripos($currdir,ROOT_PATH."..")===false){
                    chdir($currdir);
                }
            }
        }
        $root=getcwd();//项目根路径
        $open=opendir($root);
        $data=array();
        $num=array(
            'dir'=>0,
            'file'=>0,
        );
        while($filename=readdir($open)){
            if ($filename!="." && $filename!="..") {
                if (is_dir($filename)) {
                    $arr['icon']="#icon-wenjianjia1";
                    $num['dir']++;
                    $arr['flag']=1;
                }else{
                    $arr['icon']=$this->seticon($filename);
                    $num['file']++;
                    $arr['flag']=0;
                }
                $arr['currdir']=iconv('GB2312','UTF-8',getcwd()."\\".$filename);
                $arr['name']=$filename;
                $arr['size']=filesize($filename);
                $arr['ctime']=filectime($filename);
                $arr['mtime']=filemtime($filename);
                $data[]=$arr;
            }
        }
        // array_column — 返回数组中指定的一列
        // array_multisort — 对多个数组或多维数组进行排序
        array_multisort(array_column($data,'flag'),SORT_DESC,$data);
        $curr=input('page');
        $currpage=$this->page_array($data,10,$curr);
        $this->assign(array(
            'dirs'=>$currpage['data'],
            'page'=>$currpage['page'],
            'root'=>$root,
            'num'=>$num,
        ));
        return view();
    }
    /**
     * 文件类型
     */
    private function seticon($filename){
        $exc=strtoupper(substr($filename,strrpos($filename,".")));
        $icon='';
        switch ($exc){
            case ".HTML":
                $icon="#icon-html1";
                break;
            case ".PHP":
                $icon="#icon-PHP";
                break;
            case ".JS":
                $icon="#icon-JS";
                break;
            case ".BMP":
                $icon="#icon-BMP";
                break;
            case ".PNG":
                $icon="#icon-PNG";
                break;
            case ".JPEG":
                $icon="#icon-JPEG";
                break;
            case ".GIF":
                $icon="#icon-GIF";
                break;
            case ".CSS":
                $icon="#icon-CSS";
                break;
            case ".JPG":
                $icon="#icon-Jpg";
                break;
            case ".JSON":
                $icon="#icon-json_file__ea";
                break;
            default :
                $icon='#icon-file';
        }
        return $icon;
    }

    /**
     * 数据分页
     *@param $arr 数组
     *@param $page 每页显示的条数
     *@param $curr 当前页数
     * @return \think\Response
     */
    private function page_array($arr,$page=10,$curr)
    {   
        $total=ceil(count($arr)/$page);//进一法取整
        if ($curr<=0)$curr=1;
        if ($curr>$total)$curr=$total;
        $data=array_slice($arr,($curr-1)*$page,$page);//从数组中取出一段
        return [
            'data'=>$data,
            'page'=>[
                'count'=>count($arr),
                'limit'=>$page,
                'curr'=>$curr,
            ]
        ];
    }

    /**
     * 删除文件或目录
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delfile()
    {
       if (request()->isAjax()) {
           $file=iconv('UTF-8','GB2312',urldecode(input('file')));
           if (is_dir($file)) {
               $arr=scandir($file);//列出指定路径中的文件和目录
               if (count($arr)===2) {//判断是否为空目录
                   @rmdir($file);//删除目录
                   return json(['code'=>1,'msg'=>'目录删除成功']);
               }else {
                return json(['code'=>0,'msg'=>'目录不为空不能删除']);
               }
           }
           if (is_file($file)) {
                @unlink($file);//删除文件
                return json(['code'=>1,'msg'=>'文件删除成功']);
           }
           return json(['code'=>0,'msg'=>'文件删除失败']);
       }
    }
    /**
     * 重命名
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function rename(){
        if(request()->isAjax()){
            $file=iconv("UTF-8","GB2312",urldecode(input('file')));//编码的转换
            $filename=input('filename');
            $newfile=iconv("UTF-8","GB2312",dirname($file).DS.$filename);
            if(file_exists($newfile)){
                return json(['code'=>0,'msg'=>'文件已存在（重名）']);
            }
            @rename($file,$newfile);//重命名
            return json(['code'=>1,'msg'=>'重命名成功']);
        }
    }
    /**
     * 文件编辑
     */
    public function fileEdit(){
        $file=iconv("UTF-8","GB2312",urldecode(input('file')));
        $code=htmlentities(file_get_contents($file),ENT_COMPAT,"UTF-8");
        $arr=['.PHP','.CSS','.JS','.XML','.HTML','.HTACCESS'];
        $exc=strtoupper(substr($file,strrpos($file,".")));
        if(!in_array($exc,$arr)){
            $this->error("该文件类型不支持编辑");
        }
        if (request()->isPost()) {
            $content=input('code');
            $fp=fopen($file,'w');
            fwrite($fp,$content);
            fclose($fp);
            $this->success('文件保存成功','index');
        }
        $this->assign(array(
            'code'=>$code,
            'ext'=>$exc,
            'currfile'=>$file,
        ));
       return view();
    }
    //    文件下载
    public function download($currdir=null){
        $file=iconv('UTF-8',"GB2312",urldecode($currdir));
        if(!file_exists($file)){
            $this->error("文件不存在");
        }
        $filename=basenamecn(iconv('GB2312',"UTF-8",$file));
        header('Content-Disposition: attachment;filename='.$filename);
        readfile($file);
    }
}
